package com.wechat.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.wechat.apidoc.WxMaUserInterface;
import com.wechat.entity.User;
import com.wechat.service.UserService;
import com.wechat.utils.ActionResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 微信小程序用户接口
 *
 * @author cgc
 * @date 2018/4/11
 */
@RestController
@RequestMapping("/api/v1")
public class WxMaUserController implements WxMaUserInterface {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxMaService wxService;

    @Autowired
    private UserService userService;


    /**
     * 登陆并获取用户信息接口
     */
    @Override
    @RequestMapping(value = "/user/login",method = RequestMethod.POST)
    public ActionResult login(String code, String signature, String rawData, String encryptedData, String iv) {

        logger.info("[登录接口]:{}", "code=" + code + ",signature=" + signature + ",rawData=" + rawData + ",encryptedData=" + encryptedData + ",iv=" + iv );

        ActionResult result = new ActionResult();

        if (StringUtils.isBlank(code) || StringUtils.isBlank(signature) || StringUtils.isBlank(rawData) || StringUtils.isBlank(encryptedData) || StringUtils.isBlank(iv)) {
            result.setSuccess(false);
            result.setMessage("参数不能为空");
            return result;
        }

        try {
            WxMaJscode2SessionResult session = this.wxService.getUserService().getSessionInfo(code);
            String sessionKey = session.getSessionKey();
            String openid = session.getOpenid();
            // 用户信息校验
            if (!this.wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
                result.setSuccess(false);
                result.setMessage("用户信息校验失败");
                return result;
            }
            // 解密用户信息
            WxMaUserInfo userInfo = this.wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

            User user = userService.findByOpenId(openid);
            if(user == null){
                User newUser = new User();
                newUser.setOpenId(openid);
                newUser.setNickname(userInfo.getNickName());
                newUser.setCity(userInfo.getCity());
                newUser.setCountry(userInfo.getCountry());
                newUser.setGender(Byte.valueOf(userInfo.getGender()));
                newUser.setProvince(userInfo.getProvince());
                newUser.setAvatarUrl(userInfo.getAvatarUrl());
                userService.save(newUser);
                user = newUser;
            }

            String userCode = userService.setLoginUser(user);

            result.setData(userCode);
            result.setSuccess(true);
            result.setMessage("登录成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("登录失败");

            this.logger.error("[登录接口异常]", e);
        }

        return result;
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @Override
    @RequestMapping(value = "/user/info",method = RequestMethod.POST)
    public ActionResult info(String key) {
        logger.info("[获取用户信息接口]:{}", "key="+ key);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if(user == null){
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        try {
            User userInfo = userService.findById(user.getId());

            result.setData(userInfo);
            result.setSuccess(true);
            result.setMessage("获取用户信息成功");

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("获取用户信息失败");

            logger.warn("[获取用户信息接口异常]：", e);
        }

        return result;
    }

}
